//
//  ReadBookVOrH_VC+Activity.m
//  KidReading
//
//  Created by YangShuai on 16/10/12.
//  Copyright © 2016年 刘赞黄Telen. All rights reserved.
//

#import "ReadBookVOrH_VC+Activity.h"
#import "ConstDefine.h"
#define __activityFolder @"activitiesImages"

@implementation DownLoadActivityImage

//获取cache目录跟地址
+(NSString*)getCacheDirFilePath{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachesDir = [paths objectAtIndex:0];
    return cachesDir;
}

//获取图片下载的完整路径
+ (NSString*)filePathOfActivityImagesWithActivityName:(NSString*)activityName Type:(NSString*)type ImageName:(NSString*)imageName{
    NSString *cachesDir = [self getCacheDirFilePath];
    NSString* activitiesImageFolderPath = [cachesDir stringByAppendingPathComponent:__activityFolder];
    NSString* activityImagesFolderPath = [activitiesImageFolderPath stringByAppendingPathComponent:activityName];
    NSString* oneActivityType = [activityImagesFolderPath stringByAppendingPathComponent:type];
    NSString* imageFilePath = [oneActivityType stringByAppendingPathComponent:imageName];
    BOOL isDirectory = NO;
    BOOL isFileExists = NO;
    isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:oneActivityType isDirectory:&isDirectory];
    if (!isDirectory && isFileExists) {
        [[NSFileManager defaultManager] removeItemAtPath:oneActivityType error:nil];
    }
    if (!isDirectory || !isFileExists) {
        [[NSFileManager defaultManager] createDirectoryAtPath:oneActivityType withIntermediateDirectories:YES attributes:nil error:NULL];
    }
    return imageFilePath;
}
//确定活动图片是否已经存在
+(BOOL)activityImageIsExistWithActivityName:(NSString*)activityName Type:(NSString*)type ImageName:(NSString*)imageName{
    BOOL isExist = NO;
    NSString* imagePath = [self filePathOfActivityImagesWithActivityName:activityName Type:type ImageName:imageName];
    if ([[NSFileManager defaultManager] fileExistsAtPath:imagePath]) {
        isExist = YES;
    }
    return isExist;
}
//获取对应路径的UIimage
+(UIImage*)getImageWithActivityName:(NSString*)activityName Type:(NSString*)type ImageName:(NSString*)imageName{
    UIImage* image = nil;
    NSString* imagePath = [self filePathOfActivityImagesWithActivityName:activityName Type:type ImageName:imageName];
    image = [[UIImage alloc] initWithContentsOfFile:imagePath];
    return image;
}
//下载图片
+(void)downloadActivityImageWithImageUrlArray:(NSArray*)imageUrlArray ActivityName:(NSString*)activityName Type:(NSString*)type AllComplete:(void(^)(NSArray* imageArray))allComplete{
    __block NSInteger completeCount = 0;
    NSMutableArray* imageArray = [NSMutableArray new];
    void(^isAllComplete)() = ^(){
        if (completeCount == imageUrlArray.count) {
            if (allComplete) allComplete(imageArray);
        }
    };
    
    for (NSString* imageUrl in imageUrlArray) {
        NSString* imageName = [imageUrl lastPathComponent];
        if ([self activityImageIsExistWithActivityName:activityName Type:type ImageName:imageName]) {
            //图片已下载
            [imageArray addObject:[self getImageWithActivityName:activityName Type:type ImageName:imageName]];
            completeCount++;
            isAllComplete();
        }else{
            //图片为下载
            [[JRSDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:imageUrl] options:0 progress:nil completed:^(UIImage *image, NSError *error, JRSDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
                if (image) {
                    //保存到本地
                    NSData* imageData = UIImagePNGRepresentation(image);
                    [imageData writeToFile:[self filePathOfActivityImagesWithActivityName:activityName Type:type ImageName:imageName] atomically:YES];
                    [imageArray addObject:image];
                    completeCount++;
                    isAllComplete();
                }
            }];
        }
    }
}
@end


@interface ReadBookVOrH_VC()
@property(nonatomic,strong)UIImageView* flagImageView;
@property(nonatomic,strong)NSArray* imageArray;
@property(nonatomic,strong)AIActionView* aniView;
@property(nonatomic,strong)ActivityBubbleViewController* activityBubble;
@end


@implementation ReadBookVOrH_VC (Activity)

ASSOCIATED(flagImageView, setFlagImageView, UIImageView*, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
ASSOCIATED(imageArray, setImageArray, NSArray*, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
ASSOCIATED(aniView, setAniView, AIActionView*, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
ASSOCIATED(activityBubble, setActivityBubble, ActivityBubbleViewController*, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

+ (void)load
{
    [self swizzleSelector:@selector(viewDidLoad) withSelector:@selector(viewDidLoad_activity)];
    [self swizzleSelector:@selector(readViewDidScrolledTo:) withSelector:@selector(readViewDidScrolledTo_activity:)];
}
//
- (void)viewDidLoad_activity
{
    [self viewDidLoad_activity];
    //下载本书需要的活动图片
    [self downLoadActivityImages];
    //获取活动分享需要显示的分享图标
    [self getReaderInsideOperMap];
}
//获取活动需要分享的选项
- (void)getReaderInsideOperMap{
    [[NetGetPostsWithCache shareInstance] getReaderInsideActivityInfoWithBookId:self.bookid success:^(NSDictionary *retDict) {
        //NSLog(@"%@",retDict);
        self.readerInsideOperMap = retDict;
    } failure:^(NSError *error) {
        //NSLog(@"%@",error);
    }];
}
//下载书本需要的活动图片
-(void)downLoadActivityImages{
    NSArray* allActivityKeys = [self.operMap allKeys];
    for (NSString* oneKey in allActivityKeys) {
        NSDictionary* oneActivityInfoDict = self.operMap[oneKey];
        NSArray* gAniArray = oneActivityInfoDict[@"gAnimaList"];
        NSMutableArray* imageUrlArray = [NSMutableArray new];
        for (NSDictionary* oneAniDict in gAniArray) {
            [imageUrlArray addObject:oneAniDict[@"gaUrl"]];
        }
        [DownLoadActivityImage downloadActivityImageWithImageUrlArray:imageUrlArray ActivityName:oneKey Type:oneActivityInfoDict[@"gCode"] AllComplete:^(NSArray *imageArray) {
            self.imageArray = imageArray;
            self.activityImageDCom = YES;
        }];
    }
}

-(void)addActivityLogo{
    HangMenuForCover* hangMenus = [NSObject msgToTarget:self menthed:@"hangMenus" refs:nil needReturnValue:YES];
    //
    UIButton* flagButton = [UIButton buttonWithType:UIButtonTypeCustom];
    flagButton.adjustsImageWhenHighlighted = NO;
    [flagButton addTarget: self action:@selector(tapFlagButton:) forControlEvents:UIControlEventTouchUpInside];
    [flagButton JRSD_setBackgroundImageWithURL:[NSURL URLWithString:self.operMap[@"hwInfo"][@"decorate"]] forState:UIControlStateNormal completed:nil];
    [self.view addSubview:flagButton];
    [flagButton JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.centerX.JRMAS_equalTo(hangMenus);
        make.top.JRMAS_equalTo(hangMenus.JRMAS_bottom).offset(20);
        make.height.width.JRMAS_equalTo(hangMenus.JRMAS_width);
    }];
}

-(void)tapFlagButton:(UIButton*)button{
    [[[AFViewShaker alloc] initWithViewsArray:@[button]] shake];
}

//
- (void)readViewDidScrolledTo_activity:(PageView *)pageView
{
    [self readViewDidScrolledTo_activity:pageView];
    if (pageView.pageIndex == [self.operMap[@"hwInfo"][@"pageIndex"] integerValue]) {
        //
        if (self.activityImageDCom) {
            //
            [self showGostAni];
        }
    }else{
        if (self.aniView) {
            [DataProcess do_Main:^{
                [self.aniView unShow_and_remove];
            } delay:0.3];
        }
        if (self.activityBubble) {
            [self.activityBubble unShowAndRemove];
        }
    }
}

-(void)showGostAni{
    UIImage* firstImage = [self.imageArray firstObject];
    CGSize showSize = CGSizeMake(firstImage.size.width / 2 / ratio_w, firstImage.size.height / 2 / ratio_w);
    //
    AIActionView* aiview = [AIActionView aiActionViewWidthSize:showSize superView:self.view];
    //aiview.movePod = firstImage.size.height / 3;
    aiview.contentView.backgroundColor = [UIColor clearColor];
    [aiview showRandom_movingRandom];
    //
    UIImageView* aniImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, showSize.width, showSize.height)];
    aniImageView.image = firstImage;
    [aiview.contentView addSubview:aniImageView];
    aniImageView.animationImages = self.imageArray;
    aniImageView.animationDuration = 1;
    aniImageView.animationRepeatCount = 9999;
    [aniImageView startAnimating];
    //
    aiview.unShowTil = 15;
    //
    [aiview setClicked_tapCallBack:^(AIActionView * aview) {
        if (aview.isanimating) {
            [aview pauseAni];
            if (!self.isCatched) {
                [self tryToCacheZheGost];
            }else{
                [self showGostInfo];
            }
        }
    }];
    //
    self.aniView = aiview;
}


-(void)tryToCacheZheGost{
    [[NetGetPostsWithCache shareInstance] cacheGostWithGID:[self.operMap[@"hwInfo"][@"gId"] integerValue] Success:^(NSDictionary *retDict) {
        [self showGostInfo];
        //同步发现页
        self.isCatched = YES;
        [BaseVCManager refreshDataForAllBaseVCWithOutReadVC];
        [[RootViewController shareLastInstance] cleanLimitedDateAndReflashLibrary];
    } failure:^(NSError *error) {
        [UIAlertView tl_showTitle:@"" message:NSLocalizedString(@"needNetCacheGost", nil) didClick:^(UIAlertView * _Nullable alertView, NSInteger buttonIndex) {
        } buttonTitles:@"取消",nil];
    }];
}

-(void)showGostInfo{
    //提示鬼的信息
    ActivityBubbleViewController* activityBubble = [[ActivityBubbleViewController alloc] init];
    activityBubble.followView = self.aniView;
    NSString* showText = [NSString stringWithFormat:@"%@\n\n%@",self.operMap[@"hwInfo"][@"gIntro"],self.operMap[@"hwInfo"][@"bottomInfo"]];
    [activityBubble showBubbleViewToActivityVC:self Introduce:showText];
    self.activityBubble = activityBubble;
    activityBubble.dismissBlock = ^(){
        [self.aniView unShow_and_remove],self.aniView = nil;
    };
}


@end
